/* 
 * All pages initialization code
 * To be included in every head
 * 
 */

dbCon = new dbController();
fc = new fileController();
cCon = new cacheController();
cCon.init();
sCon = new supportController();


function checkConnection() {
    return navigator.onLine;
}

function noNetworkError(backTo){
	sessionStorage.feedback = "No network service available.";
	sessionStorage.backTo = backTo;
	$.mobile.changePage("dialog/feedbackPopup.html", {
        transition: "pop", 
        role: "dialog", 
        reverse: false
    } );
}

function showError(error, backTo){
    sessionStorage.feedback = error;
	sessionStorage.backTo = backTo;
	$.mobile.changePage("dialog/feedbackPopup.html", {
        transition: "pop", 
        role: "dialog", 
        reverse: false
    } );
}

//check minimum support

console.log("checking support");
if (!sCon.checkMinSupport()){
    console.log("min support no");
    $.mobile.changePage("dialog/notSupportedPopup.html", {
        transition: "pop", 
        role: "dialog", 
        reverse: false
    } );
}
else{
    console.log("min support ok");
}



$(window).resize(function(){
    var curPag = $('.ui-page-active').attr('id');
    
    if (curPag == "albumView") layoutAV();
    else if (curPag == "effectView") layoutEV();
    else if (curPag == "imageDrawView") layoutIDV();
    else if (curPag == "photoView") layoutPV();
    else if (curPag == "rotateView") layoutRV();
    else if (curPag == "index") layoutIndex();

});


/*
 * fullscreen image positioning
 */
//assumo che id abbia un parent che si chiama come lui, con in più "Parent"
function setFullscreen(id, iw, ih){
    //    console.log("setFullscreen");
    var img = $("#"+id);
    var par = $("#"+id+"Parent");
    
    var pw = par.width();
    var ph = par.height();
    
    if (pw==0 || ph==0) return;

    //    console.log("pw="+pw+", ph="+ph+", iw="+iw+", ih="+ih);
    var scaledDim = scaleToFit(iw, ih, pw, ph);
    if (scaledDim != null){
        var sw = scaledDim[0];
        var sh = scaledDim[1];
        img.width(sw);
        img.height(sh);
        //new image dimensions
        iw = sw;
        ih = sh;
    //        console.log("scaled: sw="+sw+", sh="+sh);
    }
    img.css("margin-left", (pw-iw)/2);
    img.css("margin-top", (ph-ih)/2);
}

//width, height, conteinerWidth, containerHeight
function scaleToFit(w, h, cw, ch){
    if (w<=cw && h<=ch) return null;
    var ratio = Math.min(cw/w, ch/h);
    var resW = Math.floor(ratio*w);
    var resH = Math.floor(ratio*h);
    return new Array(resW, resH);
}

/*
 * albumView
 */

console.log("albumView pageinit"); 

function layoutAV(){
    //    console.log("layoutAV");
    //adjust content size
    var the_height = ($(window).height() - $("#albumView").find('[data-role="header"]').height() - $("#albumView").find('[data-role="footer"]').height());
    $("#albumView").height($(window).height()).find('[data-role="content"]').height(the_height);
    $("#albumView").css('padding', 0);
    $("#albumView").height($(window).height() - $("#albumView").find('[data-role="footer"]').height());
    $("#albumView").find('[data-role="content"]').css('padding', 0); 
    
    if (photos.length == 0){
        $(".yesPhotos").hide();
    }
    else{
        $(".noPhotos").hide();
        setImageShown(AVidx);
        setGallery();
    }
}

function setGallery(){
    //    console.log("setGallery");
    
    var m = 2, f=4, d = 80;
    
    var cvs = document.getElementById("AVphotoList");
    var ctx = cvs.getContext('2d'); 
    
    cvs.width = (2*m + 2*f + d)*photos.length;
    cvs.height = 2*m + 2*f + d;
    
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    for (var i=0; i<photos.length; i++){
        ctx.fillStyle = "#fff";      
        ctx.beginPath();
        ctx.rect(m+i*(2*m+2*f+d), m, d+2*f, d+2*f);
        ctx.closePath();
        ctx.fill();
         
        var ph = new Image();  
        ph.idx = i;
        ph.onload=function(){
            var idx = this.idx;
            var m = 2, f=4, d = 80;
            var cv = document.getElementById("AVphotoList");
            var ct = cv.getContext('2d');
            
            var sc = scaleToFit(this.width, this.height, d, d);
            var scW, scH;
            if (sc != null){
                scW = sc[0];
                scH = sc[1];
            }
            else{
                scW = this.width;
                scH = this.height;
            }
            
            ct.drawImage(this, m+f+idx*(2*m+2*f+d)+(d-scW)/2, m+f+(d-scH)/2,scW, scH);
        }
        var ts = cCon.getTimestamp(photos[i].id);
        ph.src = photos[i].path+ts;
    }
    
}

$("#AVphotoList").live("swiperight", function(e){
    swiping = true;
    var ml = $('#AVphotoList').css("margin-left");
    ml = parseInt(ml.split("px")[0]);
    //    console.log("swipeleft: mL = " + ml);
    if (ml >= 0) return;
    $('#AVphotoList').animate({
        marginLeft: '+=300'
    }, 1000, function() {
        //        console.log("animato");
        swiping = false;
    });
});

$("#AVphotoList").live("swipeleft", function(e){
    swiping = true;
    var w = $('#AVphotoList').width();
    var ml = $('#AVphotoList').css("margin-left");
    ml = parseInt(ml.split("px")[0]);
    //    console.log("swipeleft: mL = " + ml);
    //    console.log("swipeleft: w = " + w);
    var controllo = ml + w;
    //    console.log("swipeleft: cont = " + controllo);
    if (controllo <= 300) return;
    $('#AVphotoList').animate({
        marginLeft: '-=300'
    }, 1000, function() {
        //        console.log("animato");
        swiping = false;
    });
});

$("#AVphotoList").live("vclick", function(e){
    if (swiping) return;
    $.mobile.showPageLoadingMsg("a", "Loading image...");
    var m = 2, f=4, d = 80;  
    
    var pos = $("#AVphotoList").offset();
    var l = pos.left;
    var t = pos.top;
    
    var x = e.pageX - l;
    var y = e.pageY - t;
    
    //    console.log("px="+e.pageX+", py="+e.pageY);
    //    console.log("l="+l+", t="+t);
    //    console.log("x="+x+", y="+y);
    
    for (var i=0; i<photos.length; i++){
        //rettangolo bianco: ctx.rect(m+i*(2*m+2*f+d), m, d+2*f, d+2*f);
        var rl = m+i*(2*m+2*f+d);
        var rr = rl + d+2*f;
        var rt = m;
        var rb = rt + d+2*f;
        if (x>=rl && x<=rr && y>=rt && y<=rb){
            setImageShown(i);
            AVidx = i;
            //            console.log("clicked: "+i);
            break;
        }
    }
});

  
function setImageShown(i){
    $.mobile.showPageLoadingMsg("a", "Loading image...");
    //    console.log("setImageShown: "+i);
    var p = photos[i];
    //    console.log(i);
    //    console.log(photos);
    var img = new Image();
    img.onload = function(){
        //        console.log("onload");
        var ts = cCon.getTimestamp(p.id);
        $("#AVimageShown").attr("src", p.path+ts);
        setFullscreen("AVimageShown", this.width, this.height);
        $.mobile.hidePageLoadingMsg();
    }
    var ts = cCon.getTimestamp(p.id);
    img.src = p.path+ts;
    sessionStorage.pid = p.id;
}

/*           
$("#AVsubmit").live("click", function(){
    $.mobile.showPageLoadingMsg("a", "Loading image...");
})
*/
$("#AVform").live("submit", function(){
    console.log("cliccato submit");
   if(!checkConnection()){
       console.log("AVform no connection");
        noNetworkError("../albumView.html");
        return false;
   }
   $.mobile.showPageLoadingMsg("a", "Loading image...");
   console.log("AVform yes connection");
   $(this).ajaxSubmit({
        type: "POST",
        url: "../../upload.php",
        success: function(r) {
            console.log ("form mandato");
            console.log(JSON.stringify(r));
            if (r == "Error"){
                $.mobile.hidePageLoadingMsg();
                showError("Can't upload your photo right now. Please try again.", "../albumView.html");
                return;
            }
            sessionStorage.tmpName = r;
            $.mobile.changePage("../photoDetailsView.html");
        }
    });
    return false;
});


/*
 * editDetailsView
 */

console.log("editDetailsView pageinit");

function saveEDV(){
    var n = $("#EDVname").val();
    var d = $("#EDVdescription").val();
    var l = $("#EDVloc").val();
    var c = $("#EDVcont").val();
    sessionStorage.tempPhoto = JSON.stringify(new photo(p.path, n, d, l, albumId, c));
}

function restoreEDV(){
    var tempPhoto = JSON.parse(sessionStorage.tempPhoto);
    sessionStorage.tempPhoto = null;
	
    console.log("tempPhoto: "+JSON.stringify(tempPhoto));
	
    if (tempPhoto.name != null) $("#EDVname").val(tempPhoto.name);
    if (tempPhoto.caption != null) $("#EDVdescription").val(tempPhoto.caption);
    if (tempPhoto.location != null) $("#EDVloc").val(tempPhoto.location);
    if (tempPhoto.contacts != null) $("#EDVcont").val(tempPhoto.contacts);

}
                    
$("a#EDVgetLocation").live("click", function(){
    saveEDV();
    
    if(!checkConnection()){
        noNetworkError("../editDetailsView.html");
        return;
    }
    
    $.mobile.showPageLoadingMsg("a", "Getting your position...");
    console.log("getting position");
    navigator.geolocation.getCurrentPosition(function(position){
        console.log("position callback");
        var coords = position.coords;
        
        console.log(coords.latitude, coords.longitude, coords.accuracy);
        var lc = new locationController();
        lc.humanFriendlyAddrs(coords.latitude, coords.longitude, function(addrs){
            //console.log(addrs)

            $.mobile.hidePageLoadingMsg();
            //$("#EDVlocationPopup").popup('open');
            sessionStorage.geolocation = JSON.stringify(addrs);
            sessionStorage.geoWarning = (coords.accuracy > 5000 ? "true" : "false");
            $.mobile.changePage("dialog/geoPopup.html", {
                transition: "pop", 
                role: "dialog", 
                reverse: false
            } );
        });
    }); 
});

for (var i=0; i<5; i++){
    $("#GPitem"+i).live("click", function(e){
        //        console.log("setting location = "+e.target.text);
        sessionStorage.geolocation = null;
        sessionStorage.geowarning = null;
        sessionStorage.loc = e.target.text;
        $("#geoPopup").dialog('close');
    });
}
                    
$("#EDsaveButton").live("click", function(){     
    //    console.log("editing");
                        
    var n = $("#EDVname").val();
    var d = $("#EDVdescription").val();
    var l = $("#EDVloc").val();
    var c = $("#EDVcont").val();
                        
    var pp = new photo(p.path, n, d, l, albumId, c);
                        
    pp.id = p.id;

    dbCon.editPhoto(pp);
});
         
/*
 * effectView
 */

console.log("effectView pageinit");
e = new effectsHelper();

function layoutEV(){
    //    console.log("layoutEV");
    //adjust content size
    var the_height = ($(window).height() - $("#effectView").find('[data-role="header"]').height() - $("#effectView").find('[data-role="footer"]').height());
    $("#effectView").find('[data-role="content"]').css('padding', 0); 
    $("#effectView").find('[data-role="content"]').height(the_height); 
    
    var photoId = sessionStorage.pid;
    p = dbCon.getPhotoFromId(photoId);
                    
    //content width, height
    var content = $("#EVContent");
    var cw = content.width();
    var ch = content.height();
                    
    //margins
    cw = cw-20;  
    ch = ch-20;
    
    //resize previews
    var pvm = document.getElementById("EVpreviewModel");
    var w = origW;
    var h = origH;
    var ratio = Math.min(cw/w, ch/h);
    var totW = Math.floor(ratio*w);
    var totH = Math.floor(ratio*h);

    //preview max dim
    var pdW = Math.floor(totW/4);
    var pdH = Math.floor(totH/4); 
                            
    var psc = scaleToFit(w, h, pdW, pdH);
    if (psc != null){
        pvm.width = psc[0];
        pvm.height = psc[1];
    }
    //    console.log("setting pw="+pvm.width+", ph="+pvm.height);
    var pw = pvm.width;
    var ph = pvm.height;
   
    $(".lab").each(function(){
        $(this).width(pw);
    });
                            
    $(".preview").each(function(){
        $(this).height(ph);
        $(this).width(pw);
    });
    
    $(".ext").each(function(){
        $(this).height(ph);
    });


    //resize result
    var rem = document.getElementById("EVresultModel");
    var rdW = 2*pw;
    var rdH = 2*ph;
    
    if (rdW > origW || rdH > origH){
        rdW = origW;
        rdH = origH;
    }                      
    var rsc = scaleToFit(origW, origH, rdW, rdH);
    if (rsc != null){
        rem.width = rsc[0];
        rem.height = rsc[1];
    }
    var rh = rem.height;
    var rw = rem.width;
    //    console.log("setting rw="+rw+", rh="+rh);

    $("#EVresult").width(rw).height(rh);
                  
    $(".middleCol").each(function(){
        $(this).width(rw+10);
    });
    
    //center table vertically
    var tb = $("#EVeffectsTable");
    tb.css("margin-top", (ch-tb.height())/2);
}
                
$(".preview").live("click", function(){
    console.log("chosen: "+this.id);
    applyEffect(this.id);
    appliedEffects.push(this.id);
});
                    
$("#EVsaveButton").live("click", function(){
    
    if(!checkConnection()){
        sessionStorage.appliedEffects = JSON.stringify(appliedEffects);
        noNetworkError("../effectView.html");
        return;
    }
    
    var cvs = document.getElementById("EVsaveCanvas");
    $.mobile.showPageLoadingMsg("a", "Saving...");
    fc.saveImage(cvs, p.path, 
        function(){ //success
            console.log("salvata!"); 
            cCon.updateTimestamp(p.id)
            $.mobile.hidePageLoadingMsg();
            $.mobile.changePage("photoView.html");
        },
        function(){ //error
            $.mobile.hidePageLoadingMsg();
            console.log("errore!");
            sessionStorage.feedback = "Can't save your photo right now. Please try again";
            $.mobile.changePage("dialog/feedbackPopup.html", {
                transition: "pop", 
                role: "dialog", 
                reverse: false
            } );
        }
        );                              
}); 

                
function applyEffect(effect){
    e.apply(effect, "EVresult", 
        function(){
            updatePreviews();
        }
        );
    e.apply(effect, "EVsaveCanvas");
}
                
function updatePreviews(){
    var img = document.getElementById("EVresult");
    reloadImg(img, "invert");
    reloadImg(img, "sepia");
    reloadImg(img, "noise");
    reloadImg(img, "sharpen");
    reloadImg(img, "blur");
    reloadImg(img, "desaturate");
    reloadImg(img, "saturation");
    reloadImg(img, "brightness");
}    
                
function loadImg(img, id){
    var cvs = document.getElementById(id);
    var ctx = cvs.getContext('2d');
    cvs.width = img.width;
    cvs.height = img.height;
    ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
    e.apply(cvs.id, cvs.id);
}
                
function reloadImg(img, id){
    var cvs = document.getElementById(id);
    var ctx = cvs.getContext('2d');
    ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
    e.apply(cvs.id, cvs.id);
}

/*
 * IDVpopupMenu
 */

console.log("IDVpopupMenu pageinit");

$(".paletteColor").live("click", function(){
    sessionStorage.curColor = $(this).css('backgroundColor'); 
    $("#IDVchosenColor").css('backgroundColor', sessionStorage.curColor);
    $.mobile.changePage("../imageDrawView.html");
}); 

                    
$("#IDVundo").live("click", function(){
    var dr = JSON.parse(sessionStorage.draw);
    //    console.log("undo: drawings = "+sessionStorage.draw);
    dr.pop();
    sessionStorage.draw = JSON.stringify(dr);
    //    console.log("end undo: drawings = "+sessionStorage.draw);
    $.mobile.changePage("../imageDrawView.html");
});
                    
$("#IDVclear").live("click", function(){
    sessionStorage.draw = JSON.stringify(new Array());  
    $.mobile.changePage("../imageDrawView.html");
}); 

/*
 * imageDrawView
 */
sessionStorage.draw = null;
sessionStorage.curColor = null;

function layoutIDV(){
    //    console.log("layoutIDV");
    
    //adjust content size
    var the_height = ($(window).height() - $("#imageDrawView").find('[data-role="header"]').height() - $("#imageDrawView").find('[data-role="footer"]').height());
    $("#imageDrawView").height($(window).height()).find('[data-role="content"]').height(the_height);
    $("#imageDrawView").css('padding', 0);
    $("#imageDrawView").height($(window).height() - $("#imageDrawView").find('[data-role="footer"]').height());
    $("#imageDrawView").find('[data-role="content"]').css('padding', 0);  
              
    var img = document.getElementById("IDVimg");
    //    console.log("img: w="+img.width+", h="+img.height);
    var cvs = document.getElementById("IDVcvs");
                        
    var content = $("#IDVdrawContent");
    var cw = content.width();
    var ch = content.height();
    //    console.log(content);
    //    console.log("cont w="+cw+", h="+ch);

    var sc = scaleToFit(img.width, img.height, cw, ch);
    var iw, ih;
    if (sc != null){
        iw = sc[0];
        ih = sc[1];
    }
    else{
        iw = img.width;
        ih = img.height;
    }

    cvs.width = iw;
    cvs.height = ih;
    //    console.log("draw: w="+cvs.width+", h="+cvs.height);
 
    var br = new rect(iw, ih);
    setBoundingRect(br);
    
    //adjust margins
    $("#IDVcvs").css("margin-left", (cw-iw)/2);
    $("#IDVcvs").css("margin-top", (ch-ih)/2);
    var o = $("#IDVcvs").offset();
    l = o.left;
    t = o.top;
    //    console.log("t="+t+", l="+l);
    
    clearAndDraw();
}

function setBoundingRect(r){
    
    if (boundingRect == null){
        boundingRect = r;
        return;
    }
    else if (r.equals(boundingRect)) return;
    
    //transform drawing coords
    var bmpRatio = r.height / boundingRect.height;
    //    console.log("r.height="+r.height+", bR.height="+boundingRect.height+", bmpRatio="+bmpRatio);
    
    for (var i=0; i<drawings.length; i++){
        var d = drawings[i];
        var newDraw = new draw(d.color);
                  
        for (var j=0; j<d.points.length; j++){
            var pp = d.points[j];
            newDraw.addPoint(pp.x*bmpRatio, pp.y*bmpRatio);
        }
        
        drawings[i] = newDraw;
    }
    
    stroke = stroke * bmpRatio;
    //    console.log("setting stroke = "+stroke);
    
    boundingRect = r;
}

function clearAndDraw(){       
    var cvs = document.getElementById("IDVcvs");
    var ctx = cvs.getContext('2d');
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); 
                    
    var img = document.getElementById("IDVimg");
    ctx.drawImage(img, 0, 0, cvs.width, cvs.height);

    ctx.lineWidth = stroke;

    for (var i=0; i<drawings.length; i++){
        var d = drawings[i];
        if (d.points.length == 0) continue;
        
        ctx.strokeStyle = d.color;
        ctx.fillStyle = d.color;      
                
        var p = d.points[0];
                        
        ctx.beginPath();
        ctx.arc(p.x, p.y, stroke/2, 0, Math.PI*2, true);
        ctx.closePath();
        ctx.fill();
                        
                        
        for (var j=1; j<d.points.length; j++){
            p = d.points[j];
            var pp = d.points[j-1]
                            
            ctx.beginPath();
            ctx.moveTo(pp.x, pp.y);
            ctx.lineTo(p.x, p.y);
            ctx.closePath();
            ctx.stroke();
                            
            ctx.beginPath();
            ctx.arc(p.x, p.y, stroke/2, 0, Math.PI*2, true);
            ctx.closePath();
            ctx.fill();
        }
                        
    }
}

function drawOriginalBitmap(cvs, ratio){       
    var ctx = cvs.getContext('2d');
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); 
                    
    var img = document.getElementById("IDVimg");
    ctx.drawImage(img, 0, 0, cvs.width, cvs.height);

    ctx.lineWidth = stroke*ratio;

    for (var i=0; i<drawings.length; i++){
        var d = drawings[i];
        if (d.points.length == 0) continue;
        
        ctx.strokeStyle = d.color;
        ctx.fillStyle = d.color;      
                
        var p = d.points[0];
                        
        ctx.beginPath();
        ctx.arc(p.x*ratio, p.y*ratio, stroke*ratio/2, 0, Math.PI*2, true);
        ctx.closePath();
        ctx.fill();
                        
                        
        for (var j=1; j<d.points.length; j++){
            p = d.points[j];
            var pp = d.points[j-1]
                            
            ctx.beginPath();
            ctx.moveTo(pp.x*ratio, pp.y*ratio);
            ctx.lineTo(p.x*ratio, p.y*ratio);
            ctx.closePath();
            ctx.stroke();
                            
            ctx.beginPath();
            ctx.arc(p.x*ratio, p.y*ratio, stroke*ratio/2, 0, Math.PI*2, true);
            ctx.closePath();
            ctx.fill();
        }
                        
    }
}

$("#IDVmenuButton").live("click", function(){
    //    console.log("IDV menu button clicked!") ;
    sessionStorage.draw = JSON.stringify(drawings);
    sessionStorage.curColor = curColor;
});

                    
$("#IDVcancelButton").live("click", function(){
    sessionStorage.draw = null;
    sessionStorage.curColor = null;
});

$("#IDVsaveButton").live("click", function(){
    
    if(!checkConnection()){
        console.log("non ho connessione");
        sessionStorage.draw = JSON.stringify(drawings);
        sessionStorage.curColor = curColor;
        noNetworkError("../imageDrawView.html");
        return;
    }
    console.log("ho connessione");
    
    var img = document.getElementById("IDVimg");
    var drawCvs = document.getElementById("IDVcvs");
    var cvs = document.createElement("canvas");
    cvs.style.display = 'none';
    cvs.width = img.width;
    cvs.height = img.height;
    document.body.appendChild(cvs);
    
    //draw save canvas "cvs"
    drawOriginalBitmap(cvs, img.height/drawCvs.height);
    
    console.log("saving");
    sessionStorage.draw = null;
    sessionStorage.curColor = null;
    $.mobile.showPageLoadingMsg("a", "Saving...");
    fc.saveImage(cvs, p.path, 
        function(){ //success
            console.log("salvata!"); 
            cCon.updateTimestamp(p.id)
            $.mobile.hidePageLoadingMsg();
            $.mobile.changePage("photoView.html");
        },
        function(){ //error
            $.mobile.hidePageLoadingMsg();
            console.log("errore!");
            sessionStorage.feedback = "Can't save your photo right now. Please try again";
            $.mobile.changePage("dialog/feedbackPopup.html", {
                transition: "pop", 
                role: "dialog", 
                reverse: false
            } );
        }
        ); 
});                  
                    
//touch
$("#IDVcvs").live("vmousedown", function(e){   
    isDrawing = true;
                              
    var x = e.pageX - l;
    var y = e.pageY - t;
                        
    //    console.log("x="+e.pageX+ ", y="+e.pageY);
                        
    curDraw = new draw(curColor);
    drawings[drawings.length] = curDraw;
    curDraw.addPoint(x, y);

    clearAndDraw();
});
                    
$("#IDVcvs").live("vmousemove", function(e){
    if (!isDrawing){
        return;
    };
                        
    var x = e.pageX - l;
    var y = e.pageY - t;
                   
    curDraw.addPoint(x, y);

    clearAndDraw();
});
                    
$("#IDVcvs").live("vmouseup", function(e){   
    isDrawing = false;
});

/*
 * index
 */
console.log("index pageinit");

function layoutIndex(){
    //    console.log("layoutIndex");
    
    if (albums.length == 0) return;
    
    //adjust content size
    var the_height = ($(window).height() - $("#index").find('[data-role="header"]').height());
    $("#index").height($(window).height()).find('[data-role="content"]').height(the_height);
    $("#index").css('padding', 0);
    $("#index").height($(window).height());
    $("#index").find('[data-role="content"]').css('padding', 0); 
    
    var alH = $("#IalbumList").height();
    $("#IalbumList").css("margin-top", (the_height - alH)/2);
}
                    
$("#ImenuButton").live("click", function(){
    //    console.log("I menu button clicked!") ;
    //$("#IpopupMenu").popup("open");
    });
                    
//popup
$("#IsaveButton").live("click", function(e){
    console.log("saving");
    var n = document.newAlbum.name.value;
    var d = document.newAlbum.description.value;
    if (!dbCon.isExistingAlbum(n)){
        var a = new album(n,d);
        dbCon.saveAlbum(a);
        $.mobile.changePage("../index.html");
    }
    else{
        sessionStorage.feedback = "There already exists an album named "+n;
        sessionStorage.backTo = "../index.html";
        $.mobile.changePage("../dialog/feedbackPopup.html", {
            transition: "pop", 
            role: "dialog", 
            reverse: false
        } );
    }
});

//  http://stackoverflow.com/questions/10508988/html-canvas-text-overflow-ellipsis
function fittingString(c, str, maxWidth) {
    var width = c.measureText(str).width;
    var ellipsis = '…';
    var ellipsisWidth = c.measureText(ellipsis).width;
    if (width<=maxWidth || width<=ellipsisWidth) {
        return str;
    } else {
        var len = str.length;
        while (width>=maxWidth-ellipsisWidth && len-->0) {
            str = str.substring(0, len);
            width = c.measureText(str).width;
        }
        return str+ellipsis;
    }
}

function setAlbumList(){
    //    console.log("setAlbumList");  

    var m = 10, fl=20, ft=22, fr=30, fb=75, d = 160;
    var totW = 2*m+fl+fr+d;
    var totH = m+ft+fb+d;
    
    var cvs = document.getElementById("IalbumList");
    var ctx = cvs.getContext('2d');
    
    cvs.width = totW*albums.length;
    cvs.height = totH;
    
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.font = "10pt sans-serif";
    ctx.fillStyle="#000";
    
    var bgr = new Image();
    bgr.onload = function(){ 

        for (var i=0; i<albums.length; i++){
            //draw background
            ctx.drawImage(this, m+i*(totW), m, this.width, this.height);
            //draw title
            str = fittingString(ctx, albums[i].name, d);
            ctx.fillText(str, m+fl+i*(totW), m+ft+d+25);
            
            
            //draw photo
            var ph = new Image();
            var a = albums[i];
            var p = dbCon.getAPhotoFromAlbum(a.id);

            ph.idx = i;
            ph.onload=function(){
                var idx = this.idx;
                var m = 10, fl=20, ft=22, fr=30, fb=75, d = 160;
                var totW = 2*m+fl+fr+d;
                var cv = document.getElementById("IalbumList");
                var ct = cv.getContext('2d');

                var sc = scaleToFit(this.width, this.height, d, d);
                var scW, scH;
                if (sc != null){
                    scW = sc[0];
                    scH = sc[1];
                }
                else{
                    scW = this.width;
                    scH = this.height;
                }

                ct.drawImage(this, m+fl+idx*(totW)+(d-scW)/2, m+ft+(d-scH)/2,scW, scH);
            }
            if (p!=null){
                var ts = cCon.getTimestamp(p.id);
                ph.src = p.path+ts;
            }
            else{
                ph.src = "img/album/camera_big.png";
            }
        }
    }

    bgr.src = "img/album/album_big.png";

}

function setAid(id){
    sessionStorage.aid = id;
}


$("#IalbumList").live("swiperight", function(e){
    swiping = true;
    var ml = $('#IalbumList').css("margin-left");
    ml = parseInt(ml.split("px")[0]);

    if (ml >= 0) return false;
    $('#IalbumList').animate({
        marginLeft: '+=300'
    }, 1000, function() {
        //        console.log("animato");
        swiping = false;
    });
    return false;
});

$("#IalbumList").live("swipeleft", function(e){
    swiping = true;
    var w = $('#IalbumList').width();
    var ml = $('#IalbumList').css("margin-left");
    ml = parseInt(ml.split("px")[0]);

    var controllo = ml + w;

    if (controllo <= 300) return false;
    $('#IalbumList').animate({
        marginLeft: '-=300'
    }, 1000, function() {
        //        console.log("animato");
        swiping = false;
    });
        
    return false;
});

$("#IalbumList").live("vclick", function(e){
    if (swiping) return;
    var m = 10, fl=20, ft=22, fr=30, fb=75, d = 160;
    var totW = 2*m+fl+fr+d;
    var totH = m+ft+fb+d;
    
    var pos = $("#IalbumList").offset();
    var l = pos.left;
    var t = pos.top;
    
    var x = e.pageX - l;
    var y = e.pageY - t;
    
    //    console.log("px="+e.pageX+", py="+e.pageY);
    //    console.log("l="+l+", t="+t);
    //    console.log("x="+x+", y="+y);
    
    for (var i=0; i<albums.length; i++){
        //ctx.drawImage(this, m+i*(totW), m, this.width, this.height);
        var rl = m+i*(totW);
        var rr = (i+1)*totW;
        var rt = m;
        var rb = m+totH;
        if (x>=rl && x<=rr && y>=rt && y<=rb){
            setAid(albums[i].id);
            $.mobile.changePage("albumView.html");
            //            console.log("clicked: "+i);
            break;
        }
    }
});

/*
 * photoDetailsView
 */
console.log("photoDetailsView pageinit");

function savePDV(){
    var n = $("#PDVname").val();
    var d = $("#PDVdescription").val();
    var l = $("#PDVloc").val();
    var c = $("#PDVcont").val();
    sessionStorage.tempPhoto = JSON.stringify(new photo("", n, d, l, albumId, c));
}

function restorePDV(){
    var tempPhoto = JSON.parse(sessionStorage.tempPhoto);
    sessionStorage.tempPhoto = null;
	
    console.log("tempPhoto: "+JSON.stringify(tempPhoto));
	
    if (tempPhoto.name != null) $("#PDVname").val(tempPhoto.name);
    if (tempPhoto.caption != null) $("#PDVdescription").val(tempPhoto.caption);
    if (tempPhoto.location != null) $("#PDVloc").val(tempPhoto.location);
    if (tempPhoto.contacts != null) $("#PDVcont").val(tempPhoto.contacts);

}
                    
//geolocation
$("a#PDVgetLocation").live("click", function(){
    
    savePDV();
    
    if(!checkConnection()){
        noNetworkError("../photoDetailsView.html");
        return;
    }
    
    $.mobile.showPageLoadingMsg("a", "Getting your position...");
    navigator.geolocation.getCurrentPosition(function(position){
        var coords = position.coords;
        
        console.log(coords.latitude, coords.longitude, coords.accuracy);
        var lc = new locationController();
        lc.humanFriendlyAddrs(coords.latitude, coords.longitude, function(addrs){
            //console.log(addrs)

            $.mobile.hidePageLoadingMsg();
            //$("#EDVlocationPopup").popup('open');
            sessionStorage.geolocation = JSON.stringify(addrs);
            sessionStorage.geoWarning = (coords.accuracy > 5000 ? "true" : "false");
            $.mobile.changePage("dialog/geoPopup.html", {
                transition: "pop", 
                role: "dialog", 
                reverse: false
            } );
        });
    }); 
});
                    
$("#PDVsaveButton").live("click", function(){
    console.log("saving");
                        
    var n = document.newPhoto.name.value;
    var d = document.newPhoto.description.value;
    var l = document.newPhoto.location.value;
    var c = document.newPhoto.contacts.value;
                        
    p = new photo(path, n, d, l, albumId, c);
    //window.alert(p.path);

    dbCon.savePhoto(p);
});

/*
 * photoView
 */

console.log("photoView pageinit");
  
function layoutPV(){
    //    console.log("layoutPV");
    //adjust content size
    var the_height = $(window).height();
    $("#photoView").height($(window).height()).find('[data-role="content"]').height(the_height);
    $("#photoView").css('padding', 0);
    $("#photoView").find('[data-role="content"]').css('padding', 0);
    setFullscreen("PVphoto", PVinitW, PVinitH);
}  
  
$("#PVmenuButton").live("click", function(){
    //    console.log("PV menu button clicked!") ;
    //$("#PVpopupMenu").popup("open");
    });
                    
$("#PVokButton").live("click", function(){
    var photoId = sessionStorage.pid;
    dbCon.removePhoto(photoId);
});


/*
 * rotateView
 */

console.log("rotateView pageinit");

function layoutRV(){
    //    console.log("layoutRV");
                    
    //adjust content size
    var the_height = ($(window).height() - $("#rotateView").find('[data-role="header"]').height() - $("#rotateView").find('[data-role="footer"]').height());
    $("#rotateView").height($(window).height()).find('[data-role="content"]').height(the_height);
    $("#rotateView").css('padding', 0);
    $("#rotateView").height($(window).height() - $("#rotateView").find('[data-role="footer"]').height());
    $("#rotateView").find('[data-role="content"]').css('padding', 0);  
    
    var img = document.getElementById("RVimg");
    var cvs = document.getElementById("RVcvs");
    var ctx = cvs.getContext('2d');
                        
    var content = $("#RVcontent");
    var cw = content.width();
    var ch = content.height();
    //    console.log(content);
    //    console.log("cont w="+cw+", h="+ch);
                        
    var m = Math.min(cw, ch);
                        
    var sc = scaleToFit(img.width, img.height, m, m);
    var iw, ih;
    if (sc != null){
        iw = sc[0];
        ih = sc[1];
    }
    else{
        iw = img.width;
        ih = img.height;
    }
                        
    cvsInitW = iw;
    cvsInitH = ih;
    cvs.width = iw;
    cvs.height = ih;
    //    console.log("draw: w="+cvs.width+", h="+cvs.height);
    ctx.drawImage(img, 0, 0, cvs.width, cvs.height);  

    rotate(totRot, cvs);

    adjustRotationCanvas();

    
}

function adjustRotationCanvas(){
    var cvs = $("#RVcvs");
    var content = $("#RVcontent");
    
    var cw = content.width();
    var ch = content.height();
    
    var iw = cvs.width();
    var ih = cvs.height();
    
    $("#RVcvs").css("margin-left", (cw-iw)/2);
    $("#RVcvs").css("margin-top", (ch-ih)/2);
    var o = $("#RVcvs").offset();
    l = o.left;
    t = o.top;
    //    console.log("t="+t+", l="+l);

    cx = l + iw/2;
    cy = t + ih/2;
    
//    console.log("cx="+cx+", cy="+cy);

}

//degree must be multiple of 90
function rotate(degree, cvs, w, h){
    
    if (!w) w = cvsInitW;
    if (!h) h = cvsInitH;
    
    var ctx = cvs.getContext('2d');
    var img = document.getElementById("RVimg");
    
    
    
    //    console.log("degree: "+degree);
                    
    if (degree % 180 == 0){
        //rotaz multipla di 180 gradi
        //        cw = img.width;
        //        ch = img.height;
        cw = w;
        ch = h;
                        
        cvs.setAttribute('width', cw);
        cvs.setAttribute('height', ch);
                        
        ctx.translate(cw/2, ch/2);
        ctx.rotate(degree * Math.PI / 180);  
        ctx.translate(-1*cw/2, -1*ch/2);         
    }
    else{
        //        cw = img.height;
        //        ch = img.width;
        cw = h;
        ch = w;

        cvs.setAttribute('width', cw);
        cvs.setAttribute('height', ch);

        ctx.translate(cw/2, ch/2);
        ctx.rotate(degree * Math.PI / 180);  
        ctx.translate(-1*ch/2, -1*cw/2);
    }

    ctx.drawImage(img, 0, 0, w, h);
}
                    
$("#RVsaveButton").live("click", function(){
    
    if(!checkConnection()){
        sessionStorage.totRot = totRot;
        noNetworkError("../rotateView.html");
        return;
    }
    
    $.mobile.showPageLoadingMsg("a", "Saving image...");
    console.log("saving!!!");
    
    var img = document.getElementById("RVimg");
    var cvs = document.createElement("canvas");
    cvs.style.display = 'none';
    cvs.width = img.width;
    cvs.height = img.height;

    document.body.appendChild(cvs);
    rotate(totRot, cvs, img.width, img.height);

    
    fc.saveImage(cvs, p.path, 
        function(){ //success
            console.log("salvata!");
            cCon.updateTimestamp(p.id)
            $.mobile.hidePageLoadingMsg();
            $.mobile.changePage("photoView.html");
        },
        function(){ //error
            $.mobile.hidePageLoadingMsg();
            console.log("errore!");
            sessionStorage.feedback = "Can't save your photo right now. Please try again";
            $.mobile.changePage("dialog/feedbackPopup.html", {
                transition: "pop", 
                role: "dialog", 
                reverse: false
            } );
        }
        );                      
});
                    
//rotation
$("#RVcvs").live("vmousedown", function(e){     
    //console.log("cx = "+cx+", cy = " +cy );
//    console.log("x = "+e.pageX+", y = " +e.pageY);
    firstX = e.pageX;
    firstY = e.pageY;
    firstAngle = Math.atan2(cy-firstY, cx-firstX);
                        
});
                    
$("#RVcvs").live("vmouseup", function(e){
    //console.log("cx = "+cx+", cy = " +cy );
//    console.log("x = "+e.pageX+", y = " +e.pageY);  
    var lastX = e.pageX;
    var lastY = e.pageY;
    var lastAngle = Math.atan2(cy-lastY, cx-lastX);
                        
    if (lastAngle > firstAngle){
        //cw
        totRot = (totRot + 90)%360;
    }
    else{
        //ccw
        totRot = (totRot - 90)%360;
    }
//    console.log("firstAngle = "+firstAngle+", last = "+lastAngle+", totRot = "+totRot);
    var cvs = document.getElementById("RVcvs");
    rotate(totRot, cvs);
    adjustRotationCanvas();
});


/*
 * shareFbView
 */

function fbFeedback(msg){
    sessionStorage.feedback = msg;
    $.mobile.changePage("dialog/feedbackPopup.html", {
        transition: "pop", 
        role: "dialog", 
        reverse: false
    } );
}

//fb functions
function reallyPost(accessToken, p, comment){
    console.log("really post");
    //finally post
    $.mobile.showPageLoadingMsg("a", "Uploading image. Please wait...");
    FB.api('/me/photos', 'post', {
        message: comment, 
        url: p.path
    }, function(response) {
        console.log("really post response: ");
        console.log(response);
        $.mobile.hidePageLoadingMsg();
        
        if (!response || response.error ) {
            console.log("fb post error");
            fbFeedback("Can't post your photo right now. Please try again.");
        } else {
            console.log("fb post success");
            fbFeedback("Your photo has been posted.");
        }
 
    });
}

$("#SFVsaveButton").live("click", function(){
    console.log("fb save clicked");
    
    FB.getLoginStatus(function(response) {
        console.log("response is: ");
        console.log(response);
        if (response.status === 'connected') {
            console.log("fb already connected")
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
            reallyPost(accessToken, p, document.fbForm.comment.value);
        } else{
            console.log("fb must connect");
            login();
        }
    });
    
});

function login(){
    if(!checkConnection()){
        noNetworkError("../shareFbView.html");
        return;
    }
    
    FB.login(function(response) {
        console.log("response is: "+response)
        if (response.authResponse) {
            //            var accessToken = response.authResponse.accessToken;
            //            reallyPost(accessToken, p, document.fbForm.comment.value);
            $("#SFVsaveButton").click();
        } else {
            fbFeedback("You must login and authorize MyPhotoMemories to post photos on your profile.");
        }
    }, {
        scope: 'publish_stream'
    });
}